package com.example.petstoreservice.service;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.example.petstoreservice.entity.*;
import com.example.petstoreservice.mapper.OrderItemMapper;
import com.example.petstoreservice.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductService productService; // 注入 ProductService
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderItemService orderItemService;
    private Long generateOrderId() {
        long timestamp = System.currentTimeMillis(); // 当前时间戳（毫秒）
        int randomNum = new Random().nextInt(90000) + 10000; // 生成 10000 到 99999 的随机数
        return Long.parseLong(String.valueOf(timestamp) + randomNum);
    }
    public Long createOrder(String username, List<OrderData> orderDataList, String status, Long addressId, BigDecimal couponDiscount) {
        if (orderDataList.isEmpty()) {
            return 0L; // 没有选择商品
        }

        // 2. 创建订单
        Order newOrder = new Order();
        newOrder.setOrderId(generateOrderId()); // 生成订单号
        newOrder.setUserName(username);
        newOrder.setStatus(status);
        newOrder.setAddressId(addressId);
        BigDecimal totalPrice = BigDecimal.ZERO;

        // 遍历传入的商品数据，计算总价
        for (OrderData orderData : orderDataList) {
            Product product = productService.getById(orderData.getProductId());
            if (product != null && product.getStock() >= orderData.getSkuQuantity()) {
                BigDecimal quantity = BigDecimal.valueOf(orderData.getSkuQuantity());
                // 计算订单总价
                totalPrice = totalPrice.add(quantity.multiply(orderData.getItemPrice()));
            } else {
                // 如果有商品库存不足，返回 false
                return -1L;
            }
        }
        // 应用优惠券折扣
        if (couponDiscount != null) {
            BigDecimal discountValue = couponDiscount.divide(BigDecimal.valueOf(100), RoundingMode.HALF_UP);
            // 从总价中减去折扣
            totalPrice = totalPrice.subtract(discountValue);
        }

        // 确保总价不为负数
        if (totalPrice.compareTo(BigDecimal.ZERO) < 0) {
            totalPrice = BigDecimal.ZERO;
        }
        // 设置订单总价
        newOrder.setTotal(totalPrice);

        // 先保存订单到数据库
        orderMapper.insertOrder(newOrder);

        // 插入每个订单项并更新库存
        for (OrderData orderData : orderDataList) {
            Product product = productService.getById(orderData.getProductId());
            if (product != null && product.getStock() >= orderData.getSkuQuantity()) {
                BigDecimal quantity = BigDecimal.valueOf(orderData.getSkuQuantity());

                // 创建订单项
                OrderItems orderItem = new OrderItems();
                orderItem.setOrderId(newOrder.getOrderId()); // 设置已生成的订单ID
                orderItem.setProductId(product.getProductId());
                orderItem.setQuantity(Long.valueOf(orderData.getSkuQuantity()));
                orderItem.setTotal(quantity.multiply(orderData.getItemPrice()));

                // 保存订单项
                orderItemService.insertOrderItem(orderItem);
            }
        }
            for (OrderData orderData : orderDataList) {
                Product product = productService.getById(orderData.getProductId());
                if (product != null) {
                    // 更新库存
                    product.setStock(product.getStock() - orderData.getSkuQuantity());
                    productService.updateGood(product);
                }
                if("1".equals(status)){
                    cartService.deleteItemById(orderData.getCartId());
                }
        }


        return newOrder.getOrderId();
    }


    public List<Order> getAllOrders(){
        return orderMapper.getAllOrders();
    }

    public List<Order> getOrdersByUserName(String userName){
        return orderMapper.getOrdersByUserName(userName);
    }

    public boolean insertOrder(Order order){
        // 获取产品并减少库存
        Product product = productService.getById(order.getProductId());
        if(product != null && product.getStock() >= order.getAmount()) {
            product.setStock((product.getStock() - order.getAmount()));
            if (productService.updateGood(product)) {
                int affectedRows = orderMapper.insertOrder(order);
                return affectedRows > 0;
            }
        }
        return false;
    }

    public boolean updateOrder(Order order){
        int affectedRows = orderMapper.updateOrder(order);
        return affectedRows > 0;
    }

    public boolean deleteOrder(Long orderId) {
        Order order = orderMapper.getOrderByOrderId(orderId);
        if (order == null) {
            return false; // 订单不存在
        }

            List<OrderItems> orderItems = orderItemService.getByOrderId(orderId);

            for (OrderItems orderItem : orderItems) {
                // 恢复库存
                Product product = productService.getById(orderItem.getProductId());
                if (product != null) {
                    product.setStock(product.getStock() + orderItem.getQuantity());
                    productService.updateGood(product);
                }
            }
        // 删除订单
        int affectedRows = orderMapper.deleteOrder(orderId);
        return affectedRows > 0;
    }

    public Order getOrderById(Long orderId){
        return orderMapper.getOrderByOrderId(orderId);
    }
    // 更新订单状态
    public boolean updateOrderStatus(Long orderId, String status) {
        if("3".equals(status)){
            List<OrderItems> orderItems = orderItemService.getByOrderId(orderId);

            for (OrderItems orderItem : orderItems) {
                // 恢复库存
                Product product = productService.getById(orderItem.getProductId());
                if (product != null) {
                    product.setSold((int) (product.getSold() + orderItem.getQuantity()));
                    productService.updateGood(product);
                }
            }
        }
        return orderMapper.updateOrderStatus(orderId, status) > 0;
    }
    public boolean refund(Long orderId,String info){
        String status="6";
        return orderMapper.refund(orderId,info,status)>0;
    }
    public List<Order> getOrderByUsernameAndStatus(String username,String status){
        return orderMapper.getOrderByUsernameAndStatus(username,status);
    }
}